<!--  -->
<template>
  <div class="main" ref="main">
    <template>
      <div class="item" v-for="(item, index) in sentMessage" :key="index">
        <span v-if="item.medal" class="userMedal">{{ item.medal }} </span>
        <span> {{ item.name }} </span>
        <span style="color: #fd8c01">{{ item.action }}</span>
        <span style="color: skyblue">{{ item.msg }}</span>
      </div>
      <audio
        :src="danMuBroadCast"
        autoplay
        hidden
        ref="audio"
        :paused="this.$store.state.isMute"
      ></audio>
      <audio
        :src="SongUrl"
        autoplay
        hidden
        ref="Song"
        @ended="musicEnded"
      ></audio>
      <div class="musicInfo">
        <template v-if="songInfo.Title">
          <div class="musicTitle">
            <span>正在播放：</span>
            <span>{{ songInfo.Title }}-</span>
            <span>{{ songInfo.Artist }}</span>
          </div>
        </template>
        <template v-if="!songInfo.Title">
          <span style="color: skyblue"
            >输入 点歌 + 空格 + 歌曲名可进行点歌
          </span>
        </template>
        <template v-if="songArr[1]">
          <div class="musicTitle">
            <span>下一首:</span>
            <span>{{ songArr[1] }}</span>
          </div>
        </template>
        <template v-if="selfAongArr[0] && !songArr.length">
          <div class="musicTitle">
            <span>下一首:</span>
            <span>{{ selfAongArr[0] }}</span>
          </div>
        </template>
      </div>
    </template>
    <div class="progress" v-if="songInfo.Title">
      <div class="progressIcon">
        <i class="iconfont icon-icon--"></i>
        <i class="iconfont icon-xiayibu" @click="nextMusic"></i>
      </div>
      <b-progress
        class="progressA"
        :percent.sync="percentage"
        :stroke-width="8"
        :track-color="['var(--warning)', 'var(--joker)']"
      />
    </div>
  </div>
</template>

<script>
import { encode, decode } from "../utill/bilibili-data";
import { getMusicInfo } from "../request/music/index";
import { sendMessage } from '../request/live/live'
// import { Message } from "element-ui";
import store from "../store/index";
let ws = null;
let timer = null;
let timer1 = null;
export default {
  components: {},
  data() {
    return {
      // 直播间人气
      Popularity: "",
      // 发送消息
      sentMessage: [],
      roomId: "",
      // 弹幕播报语音
      danMuBroadCast: "",
      // 是否播放完毕
      isOverAudio: true,
      // 点歌
      songArr: [],
      // 自己配置的歌曲
      selfAongArr: [],
      // 歌曲信息
      songInfo: {},
      SongUrl: "",
      // 音乐进度
      percentage: 0,
    };
  },
  created() {
    sendMessage('hhh').then(res=>{
      console.log(res);
    })
  },
  mounted() {
    for (let i = 0; i < store.state.songList.length; i++) {
      this.selfAongArr.push(store.state.songList[i]);
    }
    this.roomId = new Number(store.state.uid);
    this.startWs();
    if (this.selfAongArr.length) {
      this.playSong(this.selfAongArr);
      this.selfAongArr.splice(0, 1);
    }
  },
  watch: {
    songArr() {
      if (this.songArr.length && this.isOverAudio) {
        this.playSong(this.songArr);
        this.isOverAudio = false;
      } else if (!this.songArr.length && this.isOverAudio) {
        this.$Toast.warning("歌单暂未任何歌曲，开启本地播放");
        this.playSong(this.selfAongArr);
      }
    },
    sentMessage(n) {
      if (n.length > 50) {
        this.sentMessage.splice(0, 1);
      }
    },
  },
  methods: {
    // 音频结束
    musicEnded() {
      this.isOverAudio = true;
      if (this.songArr.length) {
        this.playSong(this.songArr);
        this.songArr.splice(0, 1);
      } else if (this.selfAongArr.length) {
        this.playSong(this.selfAongArr);
        this.selfAongArr.splice(0, 1);
        store.commit("changeSongListPush");
      } else {
        return;
      }
    },
    // 手动下一曲
    nextMusic() {
      this.musicEnded();
      this.$Toast.success("下一曲");
    },
    playSong(songArry) {
      this.$refs.Song.volume = store.state.GlobalAudioValue;
      if (songArry.length) {
        getMusicInfo(songArry[0])
          .then((res) => {
            this.songInfo = res.data.content;
            this.SongUrl = res.data.content.MusicUrl;
          })
          .catch(() => {
            console.log("播放失败");
            this.$Toast.error("播放失败,自动开启下一曲");
            songArry.splice(0, 1);
            this.playSong(songArry);
          });
        timer1 = setInterval(() => {
          if (this.$refs.Song) {
            if (this.$refs.Song.currentTime) {
              let percently =
                this.$refs.Song.currentTime / this.$refs.Song.duration;
              this.percentage = Math.round(percently * 100);
              if (this.percentage === 100) {
                return (this.percentage = 0);
              }
            }
          }
        }, 50);
      }
    },
    startWs() {
      if (ws) {
        ws.close();
      }
      if (timer) {
        clearInterval(timer);
      }
      if (!this.roomId) return;
      ws = new WebSocket("ws://broadcastlv.chat.bilibili.com:2244/sub");
      ws.onopen = () => {
        ws.send(
          encode(
            JSON.stringify({
              protover: 1,
              clientver: "1.4.0",
              roomid: this.roomId,
            }),
            7
          )
        );
        ws.onmessage = async (msgEvent) => {
          const packet = await decode(msgEvent.data);
          switch (packet.op) {
            case 8:
              console.log("加入房间");
              break;
            case 3:
              var count = packet.body.count;
              store.dispatch("Popularity", count);
              break;
            case 5:
              packet.body.forEach((body) => {
                switch (body.cmd) {
                  case "DANMU_MSG":
                    this.sentMessage.push({
                      name: body.info[2][1],
                      msg: body.info[1],
                      medal: body.info[3][1],
                    });
                    if (this.$refs.main.scrollHeight) {
                      this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
                    }
                    if (
                      store.state.isMute &&
                      store.state.GlobalAudio &&
                      store.state.BarrageAudio
                    ) {
                      this.danMuBroadCast = `http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=${body.info[1]}`;
                    }
                    switch (true) {
                      case body.info[1].indexOf("点歌") !== -1:
                        this.songArr.push(
                          body.info[1].replace("点歌", " ", "")
                        );
                        this.$Toast.success(
                          `${body.info[1].replace("点歌", " ", "")} 已加入歌单`
                        );
                        if (this.$refs.main.scrollHeight) {
                          this.$refs.main.scrollTop =
                            this.$refs.main.scrollHeight;
                        }
                        break;
                      case body.info[1].indexOf("ohh") !== -1:
                        if (store.state.isMute && store.state.GlobalAudio) {
                          this.danMuBroadCast =
                            "https://down.ear0.com:3321/preview?soundid=36826&type=mp3";
                        }
                        break;
                      case body.info[1].indexOf("哈哈") !== -1:
                        if (store.state.isMute && store.state.GlobalAudio) {
                          this.danMuBroadCast =
                            "https://down.ear0.com:3321/preview?soundid=21063&type=mp3";
                        }
                        break;
                      default:
                    }
                    break;
                  case "SEND_GIFT":
                    this.sentMessage.push({
                      name: body.data.uname,
                      action: `${body.data.action} ${body.data.num} 个 ${body.data.giftName}`,
                    });
                    if (this.$refs.main.scrollHeight) {
                      this.$refs.main.scrollTop = this.$refs.main.scrollHeight;
                    }
                    if (
                      store.state.isMute &&
                      store.state.GlobalAudio &&
                      store.state.giftAudio
                    ) {
                      this.danMuBroadCast = `http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=感谢${body.data.uname}${body.data.action} ${body.data.num} 个 ${body.data.giftName}`;
                    }
                    break;
                  case "INTERACT_WORD":
                    switch (body.data.msg_type) {
                      case 1:
                        if (!store.state.interMessage) {
                          this.sentMessage.push({
                            name: `欢迎 ${body.data.uname}`,
                            msg: `进入直播间`,
                          });
                          if (
                            store.state.isMute &&
                            store.state.GlobalAudio &&
                            store.state.intoAudio
                          ) {
                            this.danMuBroadCast = `http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=欢迎${body.data.uname}进入直播间`;
                          }
                        }
                        this.$refs.main.scrollTop =
                          this.$refs.main.scrollHeight;
                        break;
                      case 2:
                        this.sentMessage.push({
                          name: `感谢`,
                          action: `${body.data.uname}的关注`,
                        });
                        this.$Toast.success(`感谢${body.data.uname}的关注`);
                        if (store.state.isMute && store.state.GlobalAudio) {
                          this.danMuBroadCast = `http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=感谢${body.data.uname}的关注`;
                        }
                        if (this.$refs.main.scrollHeight) {
                          this.$refs.main.scrollTop =
                            this.$refs.main.scrollHeight;
                        }
                        break;
                      default:
                    }
                    break;
                  // 此处省略很多其他通知类型
                  default:
                }
              });
              break;
            default:
              console.log(packet);
          }
        };
      };
      timer = setInterval(function () {
        ws.send(encode("", 2));
      }, 30000);
    },
  },
  destroyed() {
    clearInterval(timer1);
    clearInterval(timer);
    timer = null;
    timer1 = null;
  },
};
</script>
<style lang='css' scoped>
.main {
  position: relative;
  height: 215px;
  padding-left: 20px;
  text-align: left;
  overflow: scroll;
  overflow-x: hidden;
  color: rgb(133, 133, 133);
}
.main {
  margin-right: -25px;
}
.item {
  margin-top: 15px;
}
.intoLiveRoom {
  position: fixed;
  left: 30px;
  bottom: 20px;
}
.userMedal {
  display: inline-block;
  background-color: #2f7032;
  border-radius: 3px;
  padding: 3px 5px;
  color: rgb(255, 255, 255);
  font-size: 10px;
}
.userName {
  color: rgb(13, 136, 207);
}
.userText {
  color: rgb(204, 204, 204);
}
.musicInfo {
  position: fixed;
  bottom: 45px;
  right: 20px;
  color: rgba(248, 248, 248, 0.493);
}
.musicTitle {
  width: 135px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.progress {
  position: fixed;
  bottom: 35px;
  right: -35px;
  width: 190px;
}
.progressA {
  position: fixed;
  bottom: 25px;
  right: 10px;
  width: 150px;
}
.progressIcon {
  display: inline-block;
  position: absolute;
  bottom: -5px;
  left: -40px;
  cursor: pointer;
}
.progressIcon i:hover {
  color: #409eff;
}
</style>